# coding=utf-8
import os
from glob import iglob

import requests
from queue import Queue
from pathlib import Path
# 提取ts列表文件的内容，逐个拼接ts的url，形成list
from py3utils.common_util import uuid1
from py3utils.downloader import DownloadWorker
from py3utils.m3u8_util import TS2MP4


def getPlayList(filename, m3u8_url_2):
    is_endwith_line = m3u8_url_2.endswith("/")
    url_array = []

    with open(filename, encoding="utf-8") as f:
        for line in f.readlines():
            if not (line == '' or line.startswith('#')):
                line = line.rstrip("\n")
                if is_endwith_line and line.startswith("/"):
                    line = line.lstrip("/")
                line = m3u8_url_2 + line
                url_array.append(line)  # 去掉'\n'
    return url_array


# 批量下载ts文件
def loadTs(url_array, root):
    length = len(url_array)
    if not os.path.exists(root):
        os.mkdir(root)
    for i, url in enumerate(url_array):
        tsname = url[-7:]
        # tsname = str(i) + ".ts"
        path = root + tsname
        i += 1
        try:
            r = requests.get(url)
        except Exception as e:
            print("{}批量下载失败".format(url), e)
            continue
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
            print('\r' + tsname + " -->OK ({}/{}){:.2f}%".format(i, length, i * 100 / length), end='')
    print("全部ts下载完毕")


def download_by_thread(url_array, root, nb=1):
    queue = Queue(nb)
    for _ in range(nb):
        t = DownloadWorker(queue, use_proxies=True)
        t.setDaemon(True)
        t.start()
    length = len(url_array)
    for i, url in enumerate(url_array):
        # tsname = url[-7:]
        tsname = "{}.ts".format(i)
        path = root + tsname
        info = {
            "path": path,
            "url": url,
            "headers": {
                "Referer": url,
                'Connection': 'keep-alive',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 dingtalk-win/1.0.0 nw(0.14.7) DingTalk(4.6.39-Release.10) Mojo/1.0.0 Native AppType(release)',
            }
        }
        print('\r' + tsname + " -->OK ({}/{}){:.2f}%".format(i + 1, length, (i + 1) * 100 / length), end='')
        queue.put(info)
    queue.join()
    print("全部ts下载完毕")


def sign_thread():
    out_name = ""
    out_name = out_name or uuid1()
    m3u8_url_2 = "https://videos.fjhps.com"
    filename = "4DF7FA8F54CDC1D741CDF083412159C9.m3u8"
    root = "./download/" + filename.rpartition(".")[0] + "/"
    Path(root).mkdir(parents=True, exist_ok=True)
    url_array = getPlayList(filename, m3u8_url_2)
    loadTs(url_array, root)
    TS2MP4(root, out_name).scheduling()

class Twitter(object):
    pre_url = "https://video.twimg.com"
    m3u8_file_name = "kjYjkBlxspTYebQc.m3u8"


def more_thread():
    pre_url = "https://youku.kuyun-leshi.com"
    m3u8_file_name = "DAD7FB372D9D38EA35B1F9AAD0E722A6.m3u8"
    pre_url = "https://video.twimg.com"
    m3u8_file_name = "KnNbcjiOalg66_yu.m3u8"
    out_name = ""
    out_name = out_name or uuid1()

    root = "./download/" + out_name + "/"
    Path(root).mkdir(parents=True, exist_ok=True)
    url_array = getPlayList(m3u8_file_name, pre_url)
    download_by_thread(url_array, root, nb=10)
    # tsToMp4(root, out_name)
    TS2MP4(root, out_name).scheduling()


if __name__ == "__main__":
    more_thread()
